package com.csit.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.csit.bean.Pager;
import com.csit.dao.CustomerDao;
import com.csit.entity.Customer;
import com.csit.util.StringUtil;

@Repository
public class CustomerDaoImpl extends BaseDaoImpl<Customer, Integer> implements 	CustomerDao {

	public Pager queryCustomer(Pager pager, Customer customer) {
		Criteria criteria = getSession().createCriteria(Customer.class);
		if(customer.getShop()!=null){
			criteria.add(Restrictions.eq("shop", customer.getShop()));
		}
		if(customer.getCustomerType()!=null){
			criteria.add(Restrictions.eq("customerType", customer.getCustomerType()));
		}
		if(StringUtil.isNotNull(customer.getCustomerCode())){
			criteria.add(Restrictions.like("customerCode", customer.getCustomerCode(),MatchMode.ANYWHERE));
		}
		if(StringUtil.isNotNull(customer.getCustomerName())){
			criteria.add(Restrictions.like("customerName", customer.getCustomerName(), MatchMode.ANYWHERE));
		}
		
		Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult(pager.getBeginCount());
		criteria.setMaxResults(pager.getPageSize());
		criteria.addOrder(Order.asc("customerCode"));
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		return pager;
	}

}
